<template>
  <el-dialog
    v-model="visible"
    :title="isEditMode ? '编辑节点' : '添加节点'"
    width="30%"
  >
    <el-form label-position="top">
      <el-form-item>
        <template #label>
          <div style="display: flex; align-items: center; gap: 4px">
            <span>IP</span>
            <span style="color: #999; font-size: 12px"
              >(IP作为关键字，一旦输入不能修改)</span
            >
          </div>
        </template>
        <el-input
          v-model="formData.ip"
          placeholder="请输入节点IP"
          :disabled="isEditMode"
        />
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="formData.name" placeholder="请输入节点名称" />
      </el-form-item>
      <el-form-item>
        <template #label>
          <div style="display: flex; align-items: center; gap: 8px">
            <span>图标</span>
            <img
              v-if="formData.icon"
              :src="getIconUrl(formData.icon)"
              style="width: 20px; height: 20px"
            />
          </div>
        </template>
        <IconSelector v-model="formData.icon" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">
          {{ isEditMode ? '保存' : '确认' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { getIconUrl } from '@/components/topoIcons'
import IconSelector from '@/components/IconSelector.vue'
import NodeModel from '@/models/NodeModel'

const visible = ref(false)
const isEditMode = ref(false)

const formData = ref<NodeModel>(NodeModel.createDefault())

const emit = defineEmits(['confirm', 'confirmEdit'])

const show = (editData: NodeModel | null = null) => {
  if (editData) {
    isEditMode.value = true
    formData.value = editData.clone() // 使用克隆方法避免引用问题
  } else {
    isEditMode.value = false
    formData.value = NodeModel.createDefault()
  }
  visible.value = true
}

const handleConfirm = () => {
  if (isEditMode.value) {
    emit('confirmEdit', formData.value)
  } else {
    emit('confirmNew', formData.value)
  }
  visible.value = false
  formData.value = NodeModel.createDefault()
}

defineExpose({
  show,
})
</script>
